;
(function (call) {
    var zqjdjs = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        latestTime: null,
        isFirstGetTime: true,
        areaExent: {
            12: [114.94, 38.32, 119.80, 40.47], // 全市
            hhly: [108.71, 43.88, 123.66, 35.55] // 海河流域
        },
        perValue:"90,95",
        router: {
            cfg: "/business/szyb/json/zqjdjs.json",
            queryData: "/msisExtreme/queryStatistics",
        },
        stationId:[
            54517,
            54526,
            54527,
            54622,
            54528,
            54523,
            54525,
            54623,
            54428,
            54529,
            54619],
        stationName:[
            "天津市区"
            ,"东丽区"
            ,"西青区"
            ,"津南区"
            ,"北辰区"
            ,"武清区"
            ,"宝城区"
            ,"滨海新区"
            ,"蓟州区"
            ,"宁河区"
            ,"静海区"
        ], 
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
        },
        // 获取最新起报时间
        getLatestTime: function () {
            var that = this;
            $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().setVal(new Date().format("yyyy-MM-dd 08:00:00"));
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.isFirstGetTime = true;
                    GIS.Extent.Set(that.mapId, {
                        xmin: that.areaExent.hhly[0],
                        xmax: that.areaExent.hhly[2],
                        ymax: that.areaExent.hhly[1],
                        ymin: that.areaExent.hhly[3]
                    });
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");
                    $('.product-zqjdjs-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="zqjdjsDate" data-options="${item.dateOptions}" value="`+(new Date()).toString("yyyy-MM-dd")+`">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-zqjdjs-datepicker .date-panel", {
                        query: function query(val) {
                            zqjdjs.buildLastTime(function () {
                                zqjdjs.getMultiGridData();
                            });
                        }
                    });
                    that.getLatestTime(function (latestTime) {
                        if (latestTime)
                            $(".product-zqjdjs-datepicker #jsxtybDate").IDatePicker().setVal(latestTime);
                        that.buildLastTime();
                        $(".product-zqjdjs-list").find('li.default').trigger('click');
                    });
                    that.buildProContent(data.basic_pro[item.id] || []);
                    $(".cafe-tl-content i:nth-child(1)").removeClass('active')
                     if($('.cafe-tl-content i').length == 2){
                        $(".cafe-tl-content i:nth-child(1)").hide();
                        $(".cafe-tl-content i:nth-child(2)").attr('datetip', $(".cafe-tl-content i:nth-child(1)").attr('datetip'));
                     }
                })
                $(".product-zqjdjs-tab ul").append($li);
               
            })
            $(".product-zqjdjs-tab").show();
        },
        // 初始化最近起报时间
        buildLastTime: function (call) {
            var interval = $(".product-zqjdjs-tab li.active").data("model").interval;
            var baseDate = $(".product-zqjdjs-datepicker #zqjdjsDate").val() + ":00";
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhhmm")}</li>`);
                newDate.setHours(newDate.getHours() - interval);
            }
            $(".product-zqjdjs-datechange").remove();

            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
            
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-zqjdjs-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');
                if (item.group_id == 'CNVC_index' || item.group_id == 'HAIL_index') {
                    $item = $('<div>').addClass('product-item ' + item.group_id + ' indexCfg').hide();
                } else if (item.group_id == 'model') {
                    $item = $('<div>').addClass('product-item ' + 'product-' + item.group_id + '');
                }
                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);

                if (!item.content) {
                    that.buildCustomPro($item);
                    $title.append('<i></i>');
                }
                $item.append($title);
                if (typeof item.station != "undefined") {
                    var $div = $("<div></div>");
                    $div.addClass("product_station");
                    $item.append($div);
                    var i = 0;
                    for (var key in item.station) {
                        var $span = $(`<span name=${item.station[key]} class=${i === 0 ? 'active' : ''}>${key}</span>`);
                        $div.append($span);
                        $span.unbind("click").bind("click", function () {
                            $div.find("span").removeClass("active");
                            $(this).addClass("active")
                        })
                        i++;
                    }
                }

                if (item.content) {
                    var $ul = $('<ul>');
                    item.content.forEach(function (pro) {
                        var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                        if (pro.selected)
                            $li.addClass("default");
                        if (!pro.interval) {
                            pro.interval = item.interval;
                        }
                        $li.data('pro', pro);
                        if (pro.title)
                            $li.attr('title', pro.title);
                        if (pro.width)
                            $li.css("width", pro.width);
                        $ul.append($li);
                    })
                    $item.append($ul);
                }
                $(".product-zqjdjs-list").append($item);
            })
        },
        
        
        
        
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-zqjdjs-list li.active,.product-zqjdjs-list td.active").each(function () {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
         // 清除格点图层
        clearGridLayer: function (ele_id) {
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('zqjdjs-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
		addLayerManage: function (proInfo) {
            debugger
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid) {
                debugger
				that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
			}
        },
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            $(".product-zqjdjs-list li.active").each(function () {
                if ($(this).data('pro').ele_id == eleid) {
                    $(this).click();
                    return false;
                }
            })
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;

            var layers = that.getModels(pro.ele);
            var interval = pro.ele.interval*60 || 60*24;
            debugger
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                pro: pro,
                maxHour: pro.ele.maxHour || 240,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh:mm',
                    timeInterval: interval,
                    customHm: []
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function (pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);

                    that.getModelGridData(pro);
                },
                getPlayData: function (pro, timeArr) {
                    that.getModelGridData(pro, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
       // 初始化图例
		initLegentpicker: function (ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers, function (i, m) {
				layerIds.push(m.id);
			});
			CafeJS.legentPicker = CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth: 400,
				h_legend: 15,
				seq: 'decrease',
				productId: ele.color_id,
				isShowSlider: true
			});
		}, 
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            $(".product-zqjdjs-list").off('click').on('click', 'li', function () {
                var pro = $(this).data('pro');
                if ("qhpjjs"== pro.ele_id || "station"== pro.ele_id) {
                    if ($(this).hasClass("active")) {
                        $(this).removeClass("active");
                        CafeJS.ModalBoxClose("qhpjjs"== pro.ele_id ? 'zqjdjsModal':'zqjdjsModalStation');
                    } else {
						 if($(".product-zqjdjs-list li.active").length>0){
                            $(".product-zqjdjs-list li.active").click();
                         }
                        $(this).addClass("active");
						CafeJS.ModalBox({
							id: "station"== pro.ele_id ? 'zqjdjsModalStation':'zqjdjsModal',
							container: 'cafe-busis-container',
							title: "station"== pro.ele_id ? '站点':"气候平均降水阈值",
							width: 1300,
							m_top: 90,
							closeTip:false,
							m_left:575,
							//m_right: (window.innerWidth - 1200)/2,
							hide: true,
							url: "station"== pro.ele_id ? '/business/template/zqjdjsModalStation.html':'/business/template/zqjdjsModal.html',
							closed: function () {
								
							}
						});
						
                    }
                }else{
					if ($(this).hasClass("active")) {
                        $(this).removeClass("active");
                        that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id)
                        that.clearGridLayer(pro.ele_id);
                        that.removeLayer(pro);
                        
                    } else {
                        if($(".product-zqjdjs-list .active").length>0){
                            $(".product-zqjdjs-list .active").click();
                        }
                       
						$(this).addClass("active");
                        
                        that.getLatestTime(pro.ele_id);

                        that.selectedPro.push(pro);

                        var proInfo = that.getProInfo(pro);
                        // 增加产品图层
                        that.addLayerManage(proInfo);

                        that.getModelGridData(proInfo);
						
					}
					
				}
            })
            
           /** $(".qhpjjsTime").off('change').on('change', function (e) { // 日期点击
                that.loadData();
            })**/
            $('.product-zqjdjs-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
               
                e.stopPropagation();
                $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
                
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                //$(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().toNewest();
                 $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().setVal(new Date().format("yyyy-MM-dd 08:00:00"));
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            });
            $(".product-zqjdjs-tab li").first().click();
        },
         // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function (pro) {
                var proInfo = that.getProInfo(pro);
                that.getModelGridData(proInfo);
            })
            var forecastTime = that.playList.getCurTime();
            var time = $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().getVal() + ":00";
            CafeJS.layerManage.updateLayerTime(time, 'zqjdjs', forecastTime);
        },
         getProInfo: function(ele) {
            var name = $('.product-zqjdjs-tab li.active').data('model').name;
            name += '_' + ele.ele_name;
            var time = $(".product-zqjdjs-datepicker #zqjdjsDate").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'zqjdjs',
                ele: ele,
                isGrid: true,
                isSK: false,
                models:ele.models
            }
            return proInfo;
        },
        getModelGridData: function (proInfo, timeArr) {
            debugger
            var that = this;
            if (!proInfo) return;

            var pro = proInfo.ele;
            var element = pro.ele_id;
            var queryTime = that.playList.getCurTime() + ":00";
            var qbTime = new Date(proInfo.time).format('yyyy-MM-dd hh:mm:00');
            var agings = [],
                aging;
            if (timeArr) {
                timeArr.split(',').forEach(function (i) {
                    aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    aging = (Array(3).join('0') + aging).slice(-3);
                    agings.push(aging);
                })
                agings = agings.join(',');
            } else {
                agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                agings = (Array(3).join('0') + agings).slice(-3);
            }
            qbTime = new Date(qbTime).format('yyyy-MM-dd hh:mm:ss');
            var params = {
                fcstTime: qbTime,
                model: "PUB",
                aging: Number(agings),
                type: 90
            }
            if (!loading.isExist())
              loading.add();
           CafeJS.ajax({
                url: element == "grid" ? "/modelMsisExtreme/statisticsGrid":"modelMsisExtreme/statisticsEFIGrid",
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(pro.ele_id);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
		 // 绘制格点色斑图
        drawGridRawMap: function (data, pro) {
            var typeArr = this.getModels(pro);

            var color_id = pro.color_id;
            var legentCfg = CafeJS.Legentconfig().cfg();
            var colorObj = legentCfg[color_id];
            if(pro.levels){
                colorObj.levels = pro.levels;
            }
            GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
        },
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "zqjdjs-layer-" + m + "-" + pro.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: false,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        reloadData(dp){
            this.loadData();
        },
        // 加载数据
        loadData(){
            var that = this;
            $.ajax({
                url: that.router.queryData,
                async: false,
                dateType: 'json',
                data: { 
                    dateTime: $("#qhpjjsTime").val(),
                    perValue:that.perValue
                }
            }).done(function (res) {
                if (res.result && res.data){
                    that.loadTable(res);
                    that.loadCharts(res);
                } 
                
            }).fail(function () {
               
            })
        },
        loadTable(res){
            var that = this;
            var pers = that.perValue.split(",");
            var html = '<table>';
            html += '<thead>';
            html += '<tr>';
            html += '<td>区域</td>';
            that.stationName.forEach(name =>{
                html += '<td>'+name+'</td>';
            })
            html += '</tr>';
            html += '</thead><tbody>';
            for(var i=0;i<pers.length;i++){
                html += '<tr>';
                html += '<td>'+pers[i]+'%</td>';
                that.stationId.forEach(staId =>{
                    html += '<td>'+res.data[staId].list[i]+'</td>';
                })
                html += '</tr>'
            }
            html += '</tbody></table>';
            $(".zqjdjs-table").html(html);
        },
        loadCharts(res){
            var that = this;
            var pers = that.perValue.split(",");
            var seriesData = [];
            var categories = that.stationName;
            var colors=["#FEDCDA","#FEF4D6","#D6ECFA","#FEE8D4"]
            pers.forEach(function (s, i) {
                var data = [];
                that.stationId.forEach(staId =>{
                    data.push(Number(res.data[staId].list[i]));
                })
                seriesData.push({
                    name: s + "%",
                    type: 'column',
                    data: data,
                    color:colors[i]
                })
			})
            
			var trendChart = {
				title: {
                    text:"天津各站点"+$("#qhpjjsTime").val().replace("-","月")+"日气候平均降水阈值",
                    style:{
                        fontSize:"14px"
                    }
                },
				chart: {
					type:"column"
				},
				exporting: {
					enabled: false
                },
                credits:{
                    enabled:false
                },
				tooltip: {
					shared: true,
                    useHTML: true,
                    
					
				},
				plotOptions: {
					series: {
						connectNulls: true,
						marker: {
							symbol: 'circle'
                        },
                        /*dataLabels:{
                            enabled:true,
                            formatter:function(){
                                return this.point.y+"mm"
                            }
                        }*/
					}
				},
				xAxis: {
					categories: categories,
					
				},
				yAxis: {
					title: {
                        text:"降水量：mm"
                    }
				},
				series: seriesData
			};
			
			Highcharts.chart('zqjdjsChart', trendChart);
        },
    }
    
    if (typeof call === 'function') {
        CafeJS.zqjdjs = zqjdjs;
        call(zqjdjs);
    }
    window.zqjdjs = zqjdjs;
})(function (zqjdjs) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2', 'timeLine3'], function () {
        zqjdjs.init();
    });
});
